
#include <cinatra/cinatra.hpp>
#include <cinatra/middleware/cookie.hpp>
#include <cinatra/middleware/session.hpp>
#include <cinatra/json/json.hpp>


cinatra::Json::array arr;


int main()
{
	cinatra::Cinatra<> app;
	arr.emplace_back(cinatra::Json::object
	{
		{ "productid","FI-SW-01" },
		{ "productname" , "Koi" },
		{ "unitcost" , 10.00 }
	});

	arr.emplace_back(cinatra::Json::object
	{
		{ "productid","K9-DL-01" },
		{ "productname" , "Dalmation" },
		{ "unitcost" , 12.00 }
	});

	arr.emplace_back(cinatra::Json::object
	{
		{ "productid","RP-SN-01" },
		{ "productname","Rattlesnake" },
		{ "unitcost",12.00 }
	});

	arr.emplace_back(cinatra::Json::object
	{
		{ "productid","RP-SN-01" },
		{ "productname","Rattlesnake" },
		{ "unitcost",12.00 }
	});

	arr.emplace_back(cinatra::Json::object
	{
		{ "productid","RP-LI-02" },
		{ "productname","Iguana" },
		{ "unitcost",12.00 }
	});

	arr.emplace_back(cinatra::Json::object
	{
		{ "productid","FL-DSH-01" },
		{ "productname","Manx" },
		{ "unitcost",12.00 }
	});

	arr.emplace_back(cinatra::Json::object
	{
		{ "productid","FL-DSH-01" },
		{ "productname","Manx" },
		{ "unitcost",12.00 }
	});

	arr.emplace_back(cinatra::Json::object
	{
		{ "productid","FL-DLH-02" },
		{ "productname","Persian" },
		{ "unitcost",12.00 }
	});

	arr.emplace_back(cinatra::Json::object
	{
		{ "productid","FL-DLH-02" },
		{ "productname","Persian" },
		{ "unitcost",12.00 }
	});

	arr.emplace_back(cinatra::Json::object
	{
		{ "productid","AV-CB-01" },
		{ "productname","Amazon Parrot" },
		{ "unitcost",92.00 }
	});


	app.route("/", [](cinatra::Response& res)
	{
		res.end("Hello");
	});

	
	app.route("/data", [](cinatra::Response& res)
	{
		std::cout << "Get data.." << std::endl;
		cinatra::Json::object obj;
		obj.emplace("total", int(arr.size()));
		obj.emplace("rows", arr);
		res.end(cinatra::Json(obj).dump());
	});

	app.route("/del/:productid", [](std::string productid, cinatra::Response& res)
	{
		std::cout << "Delete " << productid << std::endl;
		for (auto it = arr.begin();
			it != arr.end(); ++it)
		{
			if ((*it)["productid"].string_value() == productid)
			{
				arr.erase(it);
				res.end("Success!");
				return;
			}
		}

		res.end("Failed!!!");
	});

	app.route("/add", [](cinatra::Response& res)
	{
		std::cout << "Add data" << std::endl;
		static int id = 0;
		++id;
		auto str_id = std::to_string(id);
		arr.emplace_back(cinatra::Json::object
		{
			{ "productid","NEW-PRODUCT-ID-" + str_id },
			{ "productname","NEW-NAME-" + str_id },
			{ "unitcost",id*10 }
		});

		res.end();
	});

	app.static_dir("./static").listen("8011").run();

	return 0;
}